<?php

namespace App\Controller;

use App\Logic\ContractLogic;
use App\Logic\WxPayDataLogic;

class ContractController extends ApiController 
{

	private $contract = null;
	private $wxpay = null;
	private $error = null;
    
    protected function _initialize() 
    {
        parent::_initialize();

        $this->contract = new ContractLogic();

        $this->wxpay = new WxPayDataLogic();
    }
    /**
     * app支付状态检查
     */
    public function checkAction() 
    {
        $query = array_merge(I('get.'), I('post.'));

        foreach ($query as $key => $value) 
        {
            if($value == '')
            {
                unset($query[$key]);
            }
        }

        $raw = array(
            'data' => array(),
            'msg' => '请求失败',
            'state' => 0
        );

        $required = array('contract_id','sign');
        
        $diff = array_diff($required, array_keys($query));
        
        if (empty($diff) === false) 
        {
            $raw['msg'] = 'ERROR_PARAM';
            return $this->ajaxReturn($raw);
        }

        if($this->contract->checkSign($query)===false) 
        {
            $raw['msg'] = 'ERROR_SIGN';
            return $this->ajaxReturn($raw);
        }
        
        $query['down_pay'] = str_replace(",","",$query['down_pay']);
        
        $query['total_money'] = str_replace(",","",$query['total_money']);

        $contract_data = $this->contract->getContractData($query['contract_id'],$query);
		
        if ( $contract_data == false ) {
            $raw['msg'] = 'empty return data';
            return $this->ajaxReturn($raw);
        }
        
        $raw['msg'] = '请求成功';
        $raw['state'] = 1;
        $raw['data'] = $contract_data;
        
        return $this->ajaxReturn($raw);
    }
    
    /**
     * 支付结果回调
     */
	public function notifyAction()
    {
//         $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml = file_get_contents('php://input');
//         $xml = file_get_contents(dirname(__DIR__) . '/newfile.log',FILE_APPEND);
 		var_dump($xml);exit();
        //判断异步接收的xml是否正确
        $data = $this->wxpay->FromXml($xml);

        header("Content-type: text/html; charset=utf-8");

        $xmldata = array('return_code' => 'SUCCESS','return_msg'=>'OK');

        if($data['return_code'] != 'SUCCESS')
        {
            //xml格式错误
            $xmldata = $data;
        }
        else
        {
            //判断签名是否正确
            $result_data = $data['data'];

            if($this->notifydo($result_data)===false)
            {
                $xmldata = array('return_code' => 'FAIL','return_msg'=>$this->error);
            }

            if($result_data['result_code'] != 'SUCCESS')
            {
                // 失败订单记录日志
                file_put_contents(dirname(__DIR__) . '/wxpay_notify.log','NOTIFY DATA::' . json_encode($result_data) . PHP_EOL . 'RETURN DATA::' . json_encode($xmldata). PHP_EOL,FILE_APPEND);
            }
           
        }
        echo $this->wxpay->ReplyNotify($xmldata);exit();
    }

    protected function notifydo($result_data)
    {
        $sign = $result_data['sign'];
            
        if( $this->wxpay->CheckSign($result_data,$sign) == false )
        {
           $this->error ='签名错误';
            return false;
        }
        //   取得合同编号
        $number = $result_data['attach'];

        $row = $this->contract->getDataByPar($number);

        if(!$row) 
        {
            $this->error ='合同号错误';
            return false;
        } 
		
        if($row['contract_status'] !== 1) 
        {  
            //支付金额 时间 支付状态
            $dataArr['amount'] = $result_data['total_fee'];
            $dataArr['time']   = strtotime($result_data['time_end']); 
            $dataArr['status'] = $result_data['result_code'] == 'SUCCESS' ? 1 : 2;
// 			$dataArr['trancation_raw'] = json_encode($result_data,true);
            
            if($this->contract->updateByParm($where = array('contract_number'=>$number),$dataArr) === false)
            {
                $this->error ='未知错误';
                return false;              
            } 
        }

        return true;
    }

}
